<!--家医团队-->
<template>
  <div class="p-2">
    <el-row :gutter="20">
      <el-col :lg="4" :xs="24">
        <el-card shadow="hover" style="height: 88vh;overflow:auto">
          <el-input v-model="deptName" placeholder="请输入机构名称" prefix-icon="Search" clearable />
          <el-tree
            ref="deptTreeRef"
            class="mt-2"
            node-key="id"
            :data="deptOptions"
            :props="{ label: 'label', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          />
        </el-card>
      </el-col>
      <el-col :lg="20" :xs="24">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                    :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div v-show="showSearch" class="mb-[10px]">
            <el-card shadow="hover">
              <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                <el-form-item label="团队名称" prop="teamName">
                  <el-input v-model="queryParams.teamName" placeholder="请输入团队名称" clearable
                            @keyup.enter="handleQuery"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </transition>
        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10">
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:dept:add']" type="primary" plain icon="Plus" @click="Addphp()">新增
                </el-button>
              </el-col>
            </el-row>
          </template>

          <el-table v-loading="loading" :data="phptList" height="620px">
            <el-table-column prop="deptId" align="center" label="组织编码" width="200"></el-table-column>
            <el-table-column prop="nickName" label="组织名称" width="260"></el-table-column>
            <el-table-column prop="type_name" label="组织类型" align="center" width="260"></el-table-column>
            <el-table-column prop="description" label="组织介绍" align="center" width="260"></el-table-column>
            <el-table-column prop="responsibility" label="责任人" align="center" width="260"></el-table-column>
            <el-table-column fixed="right" align="center" label="操作">
              <template #default="scope">
                <el-tooltip content="修改" placement="top">
                  <el-button v-hasPermi="['system:dept:edit']" link type="primary" icon="Edit"
                             @click="handleUpdates(scope.row)" />
                </el-tooltip>
                <el-tooltip v-if="scope.row.userId !== 1" content="删除" placement="top">
                  <el-button v-hasPermi="['system:user:remove']" link type="primary" icon="Delete"
                             @click="handleDelete(scope.row)"></el-button>
                </el-tooltip>
              </template>

            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 家庭医生添加机构信息的对话框 -->
    <el-dialog v-model="familyDoctorDialog.visible" :title="familyDoctorDialog.title" destroy-on-close append-to-body
               width="1000px">
      <el-form ref="deptFormRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="选择机构" prop="deptId">
              <el-tree-select v-model="form.deptId" :data="deptOptions"
                              :props="{ value: 'id', label: 'label', children: 'children' }"
                              @change="handleDeptChange"
                              value-key="id" placeholder="选择机构" check-strictly />
            </el-form-item>

          </el-col>

          <el-col :span="24">
            <el-form-item label="团队名称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入机构名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="组织简介" prop="description">
              <el-input type="textarea" v-model="form.description" placeholder="请输入组织简介" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="责任医生" prop="doctor_ids">
              <el-select v-model="form.doctor_ids" multiple placeholder="请选择责任医生" clearable
                         @keyup.enter="handleQuery" @change="updateTableData">
                <el-option v-for="item in doctorDictList" :key="item.userId" :label="item.userName"
                           :value="item.userId" />
              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="24">
            <el-form-item label="责任人" prop="responsibility">
              <el-select v-model="form.responsibility" placeholder="请选择责任人" clearable
                         @keyup.enter="handleQuery">
                <el-option v-for="item in tableData" :key="item.userId" :label="item.userName"
                           :value="item.userId" />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 已选医生列表 -->
          <el-table :data="tableData" style="width: 1000px" max-height="250">
            <el-table-column prop="userName" label="姓名"></el-table-column>
            <el-table-column prop="phonenumber" label="电话"></el-table-column>
            <el-table-column fixed="right" label="操作" width="100">
              <template #default="scope">
                <el-button @click.prevent="removeDoctor(scope.row)" type="text" size="small">
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForms">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="Dept" lang="ts">
import { DeptForm, DeptQuery, DeptVO } from '@/api/system/dept/types';
import { UserVO } from '@/api/system/user/types';
import api, { listUser } from '@/api/system/user';
import { getPhpDoctor, addteam, editTeam, phpdelDept } from '@/api/php/getDoctor';
import { getToken } from '@/utils/auth';

interface DeptOptionsType {
  deptId: number | string;
  deptName: string;
  children: DeptOptionsType[];
}

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));
const loading = ref(true);
const showSearch = ref(true);
const deptName = ref('');
const deptOptions = ref<DeptOptionsType[]>([]);
const isExpandAll = ref(true);
const deptUserList = ref<UserVO[]>([]);
const familyDoctorDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const phptList = ref([]);
const phptLists = ref([]);
const total = ref(0);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const deptTreeRef = ref<ElTreeInstance>();
const queryFormRef = ref<ElFormInstance>();
const deptFormRef = ref<ElFormInstance>();
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
// 当前选定的负责人 ID
const principalDoctorId = ref(null);

const initFormData = {
  deptId: undefined,
  description: undefined,
  doctor_ids: undefined,
  id: undefined,
  java_user_ids_text: undefined,
  nickName: undefined,
  responsibility: undefined,
  switch: undefined,
  typename: undefined
};
const initData = {
  form: { ...initFormData },
  queryParams: {
    organization: '家庭团队',
    authorization: 'Bearer ' + getToken(),
    clientid: import.meta.env.VITE_APP_CLIENT_ID,
    deptId: undefined
  },
  rules: {
    deptId: [{ required: true, message: '机构不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '团队名称不能为空', trigger: 'blur' }],
    description: [{ required: true, message: '团队简介不能为空', trigger: 'blur' }],
    phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
    deptCategory: [
      { min: 4, max: 6, message: '机构编码为4至6位数字', trigger: 'blur' }
    ]
  }
};
const data = reactive<PageData<DeptForm, DeptQuery>>(initData);

const { queryParams, form, rules } = toRefs<PageData<DeptForm, DeptQuery>>(data);

/** 节点单击事件 */
const handleNodeClick = async (data) => {
  queryParams.value.deptId = data.id;
  phptList.value = [];
  phptList.value = phptLists.value.filter(item => item.deptId == queryParams.value.deptId);
};


/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
/** 根据名称筛选机构树 */
watchEffect(
  () => {
    deptTreeRef.value?.filter(deptName.value);
  },
  {
    flush: 'post' // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);


// 查询团队列表
const getTeamList = async () => {
  // loading.value = true;
  const res = await getPhpDoctor(queryParams.value);
  console.log('1212',res)
  phptLists.value = res.data;
  if (phptLists.value && phptLists.value.length > 0) {
    phptList.value = phptLists.value.map(it => {
      if (it.doctor_ids && it.doctor_ids.length > 0) {
        it.doctor_ids = it.doctor_ids.split(',');
      }
      return it;
    });
  }

  loading.value = false;
};

const doctorList = async (row) => {
  console.log('1212', row);
  const res = await api.listUserByDeptId(value);
  // doctorDictList.value = res.data;
  const responsibilityIdToFind = form.responsibility;

  // // 遍历数据寻找匹配的responsibility ID并获取对应的name
  // let responsibilityName = null;
  // for (let item of res.data) {
  //   if(item.responsibility && item.responsibility.id === responsibilityIdToFind) {
  //     responsibilityName = item.responsibility.name;
  //     break;
  //   }
  // }
  //
  // console.log(`Responsibility Name: ${responsibilityName}`);
};
const doctorDictList = ref([]);
const tableData = ref([]);


const handleDeptChange = async (value) => {
  const res = await api.listUserByDeptId(value);
  doctorDictList.value = res.data;
};


//获取部门下拉树
const treeselectList = async () => {
  const res = await api.deptTreeSelect();
  deptOptions.value = res.data;
};


// 更新表格数据的方法
const updateTableData = (selectedDoctors) => {
  tableData.value = [];
  const doctorDictMap = new Map(doctorDictList.value.map(item => [item.userId, item]));
  selectedDoctors.forEach(userId => {
    const doctor = doctorDictMap.get(userId);
    if (doctor) {
      // console.log(doctor)
      tableData.value.push(doctor);
    }
  });
};

// 移除医生的方法
const removeDoctor = (doctor) => {
  tableData.value.splice(tableData.value.indexOf(doctor), 1);
  form.value.doctor_ids.splice(form.value.doctor_ids.indexOf(doctor.userId), 1);
};


/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
  familyDoctorDialog.visible = false;
};
/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  deptFormRef.value?.resetFields();
  tableData.value = [];
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getTeamList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};


/** 新增按钮操作 */
const Addphp = async (row?: DeptVO) => {
  reset();
  familyDoctorDialog.visible = true;
  familyDoctorDialog.title = '添加团队';
};


/** 修改按钮操作 */
const handleUpdates = async (row) => {
  // console.log('1111111111',row)
  reset();
  form.value = row;
  await handleDeptChange(form.value.deptId);
  await updateTableData(form.value.doctor_ids);
  familyDoctorDialog.visible = true;
  familyDoctorDialog.title = '修改团队';
};

const submitForms = () => {

  deptFormRef.value?.validate(async (valid) => {
    if (valid) {
      form.value.authorization = 'Bearer ' + getToken();
      form.value.clientid = import.meta.env.VITE_APP_CLIENT_ID;
      form.value.name = form.value.nickName;
      form.value.doctor_ids = form.value.doctor_ids.join(',');


      if (form.value.id) {
        await editTeam(form.value);
      } else {
        await addteam(form.value);
      }

      proxy?.$modal.msgSuccess('操作成功');
      familyDoctorDialog.visible = false;
      await getTeamList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row) => {
  console.log(row.id);
  const deptIdPayload = {
    authorization: 'Bearer ' + getToken(),
    clientid: import.meta.env.VITE_APP_CLIENT_ID,
    Id: row.id,
    deptId: row.deptId
  };

  try {
    const response = await phpdelDept(deptIdPayload);
    console.log('Department deleted successfully:', response);
  } catch (error) {
    console.error('Error deleting department:', error);
  }
};

onMounted(() => {
  // doctorList();
  treeselectList();
  getTeamList();
});


</script>
